package com.irdstudio.efp.nls.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.redis.redisutil.RedisUtil;
import com.irdstudio.basic.framework.redis.redisutil.keys.Ocm_Nls_Key;
import com.irdstudio.efp.console.common.psd.PsdEnumSet;
import com.irdstudio.efp.console.service.facade.PrdInfoService;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.console.service.vo.PtProductUserVO;
import com.irdstudio.efp.cus.service.facade.CusWhiteListEService;
import com.irdstudio.efp.cus.service.facade.OrgWhiteListEService;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.cus.service.vo.CusWhiteListEVO;
import com.irdstudio.efp.cus.service.vo.OrgWhiteListEVO;
import com.irdstudio.efp.esb.service.bo.req.sed.letter.ReqSedLetterBean;
import com.irdstudio.efp.esb.service.facade.EsbInvokeWrapper;
import com.irdstudio.efp.esb.service.facade.sed.letter.SedLetterInformService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.common.util.letter.MessageFactory;
import com.irdstudio.efp.nls.common.util.letter.message.*;
import com.irdstudio.efp.nls.service.facade.NlsPublicService;
import com.irdstudio.efp.nls.service.facade.NlsQueueSoltComnService;
import com.irdstudio.efp.nls.service.facade.WsApplyNotifyService;
import com.irdstudio.efp.nls.service.facade.WsApproveackConfirmService;
import com.irdstudio.efp.nls.service.vo.WsApplyNotifyVO;
import com.irdstudio.efp.nls.service.vo.WsApproveackConfirmVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import com.irdstudio.efp.rule.service.facade.TaxWithholdRemitCorpService;
import com.irdstudio.efp.rule.service.vo.TaxWithholdRemitCorpVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.Optional;

import static com.irdstudio.basic.framework.redis.redisutil.keys.Ocm_Console_Key.PRD_INFO_KEY;
import static com.irdstudio.basic.framework.redis.redisutil.keys.Ocm_Cus_Key.CUS_WHITE_LIST_E_KEY;
import static com.irdstudio.basic.framework.redis.redisutil.keys.Ocm_Cus_Key.ORG_WHITE_LIST_E_KEY;
import static com.irdstudio.basic.framework.redis.redisutil.keys.Ocm_Nls_Key.RISK_FINAL_APPLY_NOTIFY_INFO_KEY;

/**
 * 需求编号:2019D0519
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/7/17
 * 功能描述:公共服务
 * 修改日期:2019/7/17
 * 修改描述:
 */
@Service("nlsPublicService")
public class NlsPublicServiceImpl implements NlsPublicService {

    public static Logger logger = LoggerFactory.getLogger(NlsPublicServiceImpl.class);
    /**
     * 代扣代缴单位信息服务实现
     */
    @Autowired
    @Qualifier("taxWithholdRemitCorpService")
    private TaxWithholdRemitCorpService taxWithholdRemitCorpService;
    /**
     * 机构表名单服务
     */
    @Autowired
    @Qualifier("orgWhiteListEService")
    private OrgWhiteListEService orgWhiteListEService;
    /**
     * 客户白名单服务
     */
    @Autowired
    @Qualifier("cusWhiteListEService")
    private CusWhiteListEService cusWhiteListEService;

    /**
     * 产品信息服务
     */
    @Autowired
    @Qualifier("prdInfoService")
    private PrdInfoService prdInfoService;
    /**
     * 营业日期
     */
    @Autowired
    @Qualifier("pubSysInfoService")
    private PubSysInfoService pubSysInfoService;
    /**
     * 初审信息服务
     */
    @Autowired
    @Qualifier("wsApplyNotifyService")
    private WsApplyNotifyService wsApplyNotifyService;
    /**
     * 授信申请应答表
     */
    @Autowired
    @Qualifier("wsApproveackConfirmService")
    private WsApproveackConfirmService wsApproveackConfirmService;
    /***
     * redis工具类
     */
    @Autowired
    RedisUtil redisUtil;

    /**
     * 短信通知接口
     */
    @Autowired
    @Qualifier("sedLetterInformService")
    private SedLetterInformService sedLetterInformService;
    /**
     * 告警服务
     */
    @Autowired
    @Qualifier("nlsQueueSoltComnService")
    private NlsQueueSoltComnService nlsQueueSoltComnService;

    @Override
    public BigDecimal getintRateRatio(String certCode, String certType, String lmtApplySeq) {
        // 从redis中获取执行利率 客户白名单
        String cusWhite = redisUtil.get(CUS_WHITE_LIST_E_KEY.getPrefix() + lmtApplySeq);

        if (StringUtils.isNotEmpty(cusWhite)) {
            CusWhiteListEVO cusWhiteListEVOS = JSONObject.parseObject(cusWhite, CusWhiteListEVO.class);
            return cusWhiteListEVOS.getIntRateRatio();
        }
        // 从redis中获取执行利率 企业白名单
        String orgWhite = redisUtil.get(ORG_WHITE_LIST_E_KEY.getPrefix() + lmtApplySeq);
        if (StringUtils.isNotEmpty(orgWhite)) {
            OrgWhiteListEVO orgWhiteListEVO = JSONObject.parseObject(orgWhite, OrgWhiteListEVO.class);
            return orgWhiteListEVO.getIntRateRatio();
        }
        // 客户白名单
        CusWhiteListEVO cusWhiteListEVO = new CusWhiteListEVO();
        cusWhiteListEVO.setCertCode(certCode);
        cusWhiteListEVO.setCertCode(certType);
        Optional<CusWhiteListEVO> cusWhiteList = Optional.ofNullable(cusWhiteListEService.
                queryContractEle(cusWhiteListEVO));
        // 如果存在获取返回浮动利率比
        boolean isExist = cusWhiteList.isPresent();
        if (isExist) {
            return cusWhiteList.get().getIntRateRatio();
        }
        // 否则获取企业浮动利率 获取贷款代缴单位 wthldng_agnt_no
        TaxWithholdRemitCorpVO taxWithholdRemitCorpVO = taxWithholdRemitCorpService.queryWthldngCorpNm(lmtApplySeq);
        if (taxWithholdRemitCorpVO != null) {
            // 获取代扣代缴单位名称
            TaxWithholdRemitCorpVO taxWithholdRemitCorp = Optional.
                    ofNullable(taxWithholdRemitCorpService.
                            queryWthldngCorpNm(taxWithholdRemitCorpVO)).orElseGet(TaxWithholdRemitCorpVO::new);
            // 获取浮动利率
            OrgWhiteListEVO orgWhiteListEVO = new OrgWhiteListEVO();
            orgWhiteListEVO.setCompanyName(taxWithholdRemitCorp.getWthldngCorpNm());
            OrgWhiteListEVO orgWhiteList = Optional.
                    ofNullable(orgWhiteListEService.
                            queryByCompanyName(orgWhiteListEVO)).orElseGet(OrgWhiteListEVO::new);
            return orgWhiteList.getIntRateRatio();

        }

        logger.info("获取的浮动利率为空!!!");
        return null;
    }

    /**
     * 需求编号:2019D0519
     * 问题编号:
     * 开发人员: caoxin
     * 创建日期:2019/7/17
     * 功能描述:公共服务获取产品信息
     * 修改日期:2019/7/17
     * 修改描述:
     */
    public PrdInfoVO getProInfo(String proId) {
        String proStr = redisUtil.get(PRD_INFO_KEY.getPrefix() + proId);
        if (StringUtils.isNotEmpty(proStr)) {
            return JSONObject.parseObject(proStr, PrdInfoVO.class);
        }
        PrdInfoVO prdInfoVO = new PrdInfoVO();
        prdInfoVO.setPrdCode(proId);
        prdInfoVO = prdInfoService.queryLastPrdInfo(prdInfoVO);
        if (Objects.isNull(prdInfoVO)) {
            return null;
        }
        // 将产品信息放入缓存
        redisUtil.setEx(PRD_INFO_KEY.getPrefix() + proId,
                JSONObject.toJSONString(prdInfoVO),
                PRD_INFO_KEY.expireSeconds(),
                PRD_INFO_KEY.getTimeUnit());
        return prdInfoVO;
    }

    @Override
    public String getSysInfoOpenDay(String sysId) {
        // 营业日期
        String openday = pubSysInfoService.getOpenday(sysId);
        String isOpenday = Optional.ofNullable(openday).orElse("");
        if (StringUtils.isEmpty(isOpenday)) {
            logger.info("营业日期获取为空 返回空字符窜");
        }
        return isOpenday;
    }

    @Override
    public WsApplyNotifyVO getWsApplyNotify(String applyNo) {
        String wsApplyNotifyVOStr = redisUtil.get(Ocm_Nls_Key.WS_APPLY_NOTIFY_KEY.getPrefix() + applyNo);
        if (StringUtils.isNotEmpty(wsApplyNotifyVOStr)) {
            return JSONObject.parseObject(wsApplyNotifyVOStr, WsApplyNotifyVO.class);
        }
        return Optional.ofNullable(wsApplyNotifyService.queryByApplyNo(applyNo)).orElseGet(WsApplyNotifyVO::new);
    }

    @Override
    public WsApproveackConfirmVO getWsApproveackConfirm(String applyNo) {
        String wsApproveackConfirmStr = redisUtil.get(RISK_FINAL_APPLY_NOTIFY_INFO_KEY.getPrefix() + applyNo);
        if (StringUtils.isNotEmpty(wsApproveackConfirmStr)) {
            return JSONObject.parseObject(wsApproveackConfirmStr, WsApproveackConfirmVO.class);
        }
        return Optional.ofNullable(wsApproveackConfirmService.queryByApplyNo(applyNo)).orElseGet(WsApproveackConfirmVO::new);
    }

    @Override
    public void sendSuccessMessage(String phone, String approveAmt) {
        try {
            // 调用短信通知接口
            ReqSedLetterBean letter = new ReqSedLetterBean();
            letter.setMblNo(phone);
            letter.setCntntInf(new MessageFactory(new PsdCreditSuccessMessage(), Optional.ofNullable(approveAmt).orElse("0").toString(), "96699").getMessageContent());
            EsbInvokeWrapper esbInvokeWrapper = new EsbInvokeWrapper(sedLetterInformService, letter, nlsQueueSoltComnService);
            esbInvokeWrapper.invoke3Threes();
        } catch (ESBException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendFailMesage(String phone) {
        try {
            ReqSedLetterBean letter = new ReqSedLetterBean();
            letter.setMblNo(phone);
            letter.setCntntInf(new MessageFactory(new PsdCreditFailureMessage(), null).getMessageContent());
            EsbInvokeWrapper esbInvokeWrapper = new EsbInvokeWrapper(sedLetterInformService, letter, nlsQueueSoltComnService);
            esbInvokeWrapper.invoke3Threes();
        } catch (ESBException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendLmtActivatedMessage(String phone, String approveAmt) {
        try {
            // 调用短信通知接口
            ReqSedLetterBean letter = new ReqSedLetterBean();
            letter.setMblNo(phone);
            letter.setCntntInf(new MessageFactory(new PsdLmtActivatedMessage(), Optional.ofNullable(approveAmt).orElse("0").toString()).getMessageContent());
            EsbInvokeWrapper esbInvokeWrapper = new EsbInvokeWrapper(sedLetterInformService, letter, nlsQueueSoltComnService);
            esbInvokeWrapper.invoke3Threes();
        } catch (ESBException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendMessageWithCusManagerInfo(String msgType, LmtPrdContVO lmtPrdContVO, PtProductUserVO ptProductUserVO, String phone) {
        logger.info("额度激活接口分配工号后开始下发短信：短信类型{}，手机号{}", msgType, phone);
        try {
            //获取额度数据
            BigDecimal amount = lmtPrdContVO.getLmtAmt().setScale(4, BigDecimal.ROUND_HALF_UP);
            DecimalFormat df = new DecimalFormat("###,###.00");
            String approveAmt = df.format(amount);
            if (StringUtils.isEmpty(approveAmt)) {
                approveAmt = "0";
            }
            String ptName = "";
            String ptId = "";
            String ptPhone = "";
            if (!Objects.isNull(ptProductUserVO)) {
                ptName = StringUtils.isNotEmpty(ptProductUserVO.getUserName()) ? ptProductUserVO.getUserName() : "";
                ptId = StringUtils.isNotEmpty(ptProductUserVO.getLoginName()) ? ptProductUserVO.getLoginName() : "";
                ptPhone = StringUtils.isNotEmpty(ptProductUserVO.getPhone()) ? ptProductUserVO.getPhone() : "";
            }
            logger.info("额度激活接口分配工号后开始下发短信：额度{}，客户经理{}，客户经理工号{}，客户经理电话{},目标电话号{}", approveAmt, ptName, ptId, ptPhone, phone);
            // 调用短信通知接口
            ReqSedLetterBean letter = new ReqSedLetterBean();
            letter.setMblNo(phone);
            if ("1".equals(msgType)) {
                letter.setCntntInf(new MessageFactory(new PsdLmtActivatedMessage1(), approveAmt, ptName, ptId, ptPhone).getMessageContent());
            } else if ("2".equals(msgType)) {
                letter.setCntntInf(new MessageFactory(new PsdLmtActivatedMessage2(), approveAmt, ptName, ptId, ptPhone).getMessageContent());
            } else if ("3".equals(msgType)) {
                letter.setCntntInf(new MessageFactory(new PsdLmtActivatedMessage3(), approveAmt).getMessageContent());
            }
            logger.info("额度激活接口分配工号后开始下发短信：短信内容{},目标电话号{}", letter.getCntntInf(), phone);
            EsbInvokeWrapper esbInvokeWrapper = new EsbInvokeWrapper(sedLetterInformService, letter, nlsQueueSoltComnService);
            esbInvokeWrapper.invoke3Threes();
        } catch (ESBException | InterruptedException e) {
            e.printStackTrace();
            logger.error("分配客户经理后下发短信异常", e);
        }
    }

    @Override
    public void sendPsdPreApproveMessage(String phone, String approveFlag, String approveAmt) {
        try {
            logger.info("预授信收到风控审批结果{},开始发短信到号码{}", approveFlag, phone);
            if (StringUtils.isEmpty(phone)) {
                logger.error("预授信审批后下发短信异常，手机号码为空");
                return;
            }
            // 调用短信通知接口
            ReqSedLetterBean letter = new ReqSedLetterBean();
            letter.setMblNo(phone);
            String messageContent = "";
            if (PsdEnumSet.AprvlRsltFlgEnum.PASS.getValue().equals(approveFlag)) {
                messageContent = new MessageFactory(new PsdPreApproveYMessage(), approveAmt).getMessageContent();
            } else if (PsdEnumSet.AprvlRsltFlgEnum.REFUSE.getValue().equals(approveFlag)) {
                messageContent = new MessageFactory(new PsdPreApproveNMessage()).getMessageContent();
            } else if (PsdEnumSet.AprvlRsltFlgEnum.EXCEPTION.getValue().equals(approveFlag)) {
                messageContent = new MessageFactory(new PsdPreApproveEMessage()).getMessageContent();
            } else {
                logger.error("预授信审批后下发短信异常，审批结果不匹配，当前审批结果{}", approveFlag);
                return;
            }
            logger.info("预授信收到风控审批结果{},开始发短信到号码{},短信内容为{}", approveFlag, phone, messageContent);
            letter.setCntntInf(messageContent);
            EsbInvokeWrapper esbInvokeWrapper = new EsbInvokeWrapper(sedLetterInformService, letter, nlsQueueSoltComnService);
            esbInvokeWrapper.invoke3Threes();
        } catch (ESBException | InterruptedException e) {
            e.printStackTrace();
            logger.info("预授信收到风控审批结果{},开始发短信到号码{},发生异常：{}", approveFlag, phone, e.getMessage());
            logger.error("预授信审批后下发短信异常", e);
        }
    }

}
